const DB_SINGER_LIST = wx.cloud.database().collection('singerList')
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    toDeleteInfoId: ''
  },

  addData() {
    DB_SINGER_LIST.add({
      data: {
        name: '林俊杰',
        age: 30,
        songs: []
      },
      success: res => {
        console.log(res)
      }
    })
  },
  updateData() {
    DB_SINGER_LIST.doc(this.data.toDeleteInfoId).update({
      data: {
        age: 100
      },
      success: res => {
        console.log('update success: ', res.data)
      },
      fail: err => {
        console.log("update error: ", err)
      }
    })
  },
  deleteData() {
    console.log('to delete id', this.data.toDeleteInfoId)
    DB_SINGER_LIST.doc(this.data.toDeleteInfoId).remove({
      success: res => {
        console.log('delete success', res)
      },
      fail: err => {
        console.log('delete error', err)
      }
    })
  },
  queryData() {
    DB_SINGER_LIST.where({}).get({
      success: res => {
        console.log('query success', res)
        this.setData({
          toDeleteInfoId: res.data[0]._id
        })
      }
    })
  },

  getData() {
    // console.log(wx.getUserProfile)
    // this.getUserProfile()
    wx.cloud.callFunction({
      name: 'searchM',
      data: {
        keywords: '花海',
        page: 1,
        pagesize: 10
      },
      success: res => {
        console.log(res.result.data)
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  // 发起检索
  search(e) {
    const {
      value
    } = e.detail
    this.setData({
      toDeleteInfoId: value
    })
    console.log(value)
  },

  onLoad() {
    // 从缓存中获取用户信息
    wx.getStorage({
      key: 'userInfo',
      success: res => {
        if (res.data !== undefined) {
          this.setData({
            userInfo: res.data
          })
        }
      }
    })
  },

  getUserProfile() {
    if (Object.keys(this.data.userInfo).length === 0) {
      wx.getUserProfile({
        desc: '展示用户信息',
        success: (res) => {
          this.setData({
            userInfo: res.userInfo
          })

          // 存入缓存中
          wx.setStorage({
            key: 'userInfo',
            data: res.userInfo
          })

        }
      })
    }
  }
})